<template>
  <div :style="{ backgroundImage: `url(${require('@/assets/0034034892281415_b.jpg')})`,
   backgroundSize: 'cover', display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh',overflow: 'hidden'}">
    <el-card class="box-card">
      <h2>登录</h2>
      <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-position="left"
          label-width="70px"
          class="login-from"
      >
        <el-form-item label="账号" prop="uid">
          <el-input v-model="ruleForm.uid">{{user.uid}}</el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input
              type="password"
              v-model="ruleForm.pwd"
              autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-row>
            <el-col :span="16">
              <el-input v-model.trim="ruleForm.code" placeholder="请输入验证码"></el-input>
            </el-col>
            <el-col :span="8">
              <img @click="refreshCaptcha" class="code" :src="base64Image" alt="验证码图片" />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <div class="btnGroup">
        <el-button
            type="primary"
            @click="submitForm('ruleForm')"
            v-loading="loading"
        >登录</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <router-link to="/register">
          <el-button style="margin-left: 10px">注册</el-button>
        </router-link>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      ruleForm: {
        uid: "",
        pwd: "",
        code: "",
        uuid: ""
      },
      user:{
        uid: ""
      },
      rules: {
        uid: [
          { required: true, message: "账号不能为空！", trigger: "blur" },
        ],
        pwd: [
          { required: true, message: "密码不能为空！", trigger: "blur" },
        ],
        code: [      // 新增验证码字段校验规则
          { required: true, message: "验证码不能为空！", trigger: "blur" },
        ],
      },
      loading: false, // 是否显示加载动画
      base64Image: "",   // 验证码图片地址
      base64Data: ""
    };
  },
  methods: {



    submitForm(formName) {
      // 验证表单中的账号密码是否有效，因为在上面rules中定义为了必填 required: true
      this.$refs[formName].validate((valid) => {
        // 点击登录后，让登录按钮开始转圈圈（展示加载动画）
        let _this = this;
        this.loading = true;
            // 如果经过校验，账号密码都不为空，则发送请求到后端登录接口
            if (valid) {
              // 使用 axios 将登录信息发送到后端
              axios({
                url: "/api/login",               // 请求地址
                method: "post",                       // 请求方法
                headers: {                            // 请求头
                  "Content-Type": "application/json",
                },
                data: JSON.stringify({
                  id: _this.ruleForm.uid,
                  password: _this.ruleForm.pwd,
                  code: _this.ruleForm.code,
                  uuid: _this.ruleForm.uuid
                })
              }).then((res) => {
                  // 当收到后端的响应时执行该括号内的代码，res 为响应信息，也就是后端返回的信息
                  if (res.data.code === "200") {  // 当响应的编码为 200 时，说明登录成功
                    // 将用户信息存储到sessionStorage中
                    sessionStorage.setItem("userInfo", JSON.stringify(res.data.data));
                    // 跳转页面到首页
                    this.$router.push('/home');
                    // 显示后端响应的成功信息
                    this.$message({
                      message: res.data.msg,
                      type: "success",
                    });
                  } else {  // 当响应的编码不为 0 时，说明登录失败

                    // 显示后端响应的失败信息
                    this.$message({
                      message: res.data.msg,
                      type: "warning",
                    });

                    this.refreshCaptcha();
                  }

                // 不管响应成功还是失败，收到后端响应的消息后就不再让登录按钮显示加载动画了
                _this.loading = false;
                console.log(res);
              });
            } else {  // 如果账号或密码有一个没填，就直接提示必填，不向后端请求
              console.log("error submit!!");
              this.loading = false;
              return false;
            }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    refreshCaptcha() {
      axios({
        url: "/api/generateCaptcha",               // 请求地址
        method: "get",                          // 请求方法
        headers: {                            // 请求头
          "Content-Type": "application/json",
        },
      }).then( resImage => {  //锁
        console.log(resImage.data)
        this.base64Data = resImage.data.data;
        this.ruleForm.uuid = resImage.data.msg;
        console.log(this.ruleForm.uuid)
         new Promise((resolve, reject) => {
          const img = new Image();
          img.src = 'data:image/png;base64,' + this.base64Data;
          img.onload = () => {
            const canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            const context = canvas.getContext('2d');
            context.drawImage(img, 0, 0);
            this.base64Image = canvas.toDataURL();
            resolve(); // Resolve the promise once the image is loaded and processed
          };
          img.onerror = reject; // Reject the promise if there's an error loading the image
        });
      });
      //base64转为图片

    },
  },
  mounted() {
    const user = JSON.parse(sessionStorage.getItem('userInfo'))
    this.refreshCaptcha();
    if (user!=null){
      this.ruleForm.uid = user.uid
    }

  }
};
</script>

<style>
/* 设置登录面板居中，宽度为400px */
.box-card {
  margin: auto auto;
  width: 400px;
}
/* 设置登录面板中的表单居中 */
.login-from {
  margin: auto auto;
}
.code {
  position: relative;
  z-index: 1;
}
</style>
